package com.p6spy.engine.logging;

import com.p6spy.engine.common.*;
import com.p6spy.engine.event.SimpleJdbcEventListener;

import java.sql.SQLException;

/**
 * This event listener is responsible for logging the SQL statements and the execution time
 * <p>
 * To use a custom implementation for logging, extend this class and add the fully qualified class name of your
 * implementation to <code>src/main/resources/META-INF/services/com.p6spy.engine.logging.LoggingEventListener</code>.
 */
public class LoggingEventListener extends SimpleJdbcEventListener {

    public static final LoggingEventListener INSTANCE = new LoggingEventListener();

    protected LoggingEventListener() {
    }

    /**
     * 当通过P6Spy监控的Statement执行完任何操作后触发，用于记录本次执行所花费的时间及可能抛出的异常信息。
     *
     * @param statementInformation 包含执行语句详细信息的对象，如SQL文本、参数等
     * @param timeElapsedNanos     执行当前Statement所消耗的时间，单位为纳秒
     * @param e                    如果在执行过程中发生SQLException异常，则会传递给该方法；若无异常，则为null
     */
    @Override
    public void onAfterAnyExecute(StatementInformation statementInformation, long timeElapsedNanos, SQLException e) {
        // 调用自定义的日志方法，记录此次执行的耗时和相关状态（包括是否出现异常），并将其归类到"STATEMENT"类别中
        logElapsed(statementInformation, timeElapsedNanos, Category.STATEMENT, e);
    }


    @Override
    public void onAfterExecuteBatch(StatementInformation statementInformation, long timeElapsedNanos, int[] updateCounts, SQLException e) {
        logElapsed(statementInformation, timeElapsedNanos, Category.BATCH, e);
    }

    @Override
    public void onAfterCommit(ConnectionInformation connectionInformation, long timeElapsedNanos, SQLException e) {
        logElapsed(connectionInformation, timeElapsedNanos, Category.COMMIT, e);
    }

    @Override
    public void onAfterRollback(ConnectionInformation connectionInformation, long timeElapsedNanos, SQLException e) {
        logElapsed(connectionInformation, timeElapsedNanos, Category.ROLLBACK, e);
    }

    @Override
    public void onAfterAnyAddBatch(StatementInformation statementInformation, long timeElapsedNanos, SQLException e) {
        logElapsed(statementInformation, timeElapsedNanos, Category.BATCH, e);
    }

    @Override
    public void onAfterGetResultSet(StatementInformation statementInformation, long timeElapsedNanos, SQLException e) {
        logElapsed(statementInformation, timeElapsedNanos, Category.RESULTSET, e);
    }

    @Override
    public void onAfterResultSetGet(ResultSetInformation resultSetInformation, int columnIndex, Object value, SQLException e) {
        resultSetInformation.setColumnValue(Integer.toString(columnIndex), value);
    }

    @Override
    public void onAfterResultSetGet(ResultSetInformation resultSetInformation, String columnLabel, Object value, SQLException e) {
        resultSetInformation.setColumnValue(columnLabel, value);
    }

    @Override
    public void onBeforeResultSetNext(ResultSetInformation resultSetInformation) {
        if (resultSetInformation.getCurrRow() > -1) {
            // Log the columns that were accessed except on the first call to ResultSet.next().  The first time it is
            // called it is advancing to the first row.
            resultSetInformation.generateLogMessage();
        }
    }

    @Override
    public void onAfterResultSetNext(ResultSetInformation resultSetInformation, long timeElapsedNanos, boolean hasNext, SQLException e) {
        if (hasNext) {
            logElapsed(resultSetInformation, timeElapsedNanos, Category.RESULT, e);
        }
    }

    @Override
    public void onAfterResultSetClose(ResultSetInformation resultSetInformation, SQLException e) {
        if (resultSetInformation.getCurrRow() > -1) {
            // If the result set has not been advanced to the first row, there is nothing to log.
            resultSetInformation.generateLogMessage();
        }
    }

    /**
     * 使用P6Spy记录SQL查询的执行耗时。
     *
     * @param loggable         包含连接信息的Loggable对象
     * @param timeElapsedNanos 执行时间（纳秒）
     * @param category         查询所属的分类
     * @param e                SQL异常
     */
    protected void logElapsed(Loggable loggable, long timeElapsedNanos, Category category, SQLException e) {
        // 调用P6LogQuery.logElapsed方法记录查询执行时间
        P6LogQuery.logElapsed(loggable.getConnectionInformation().getConnectionId(), timeElapsedNanos, category, loggable);
    }


}
